package com.yiren.dbaa.module.project_edit.view.fragment;

import android.app.AlertDialog;
import android.app.Dialog;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.yiren.backstage.config.api.LoadConfigApi;
import com.yiren.backstage.config.enums.SiteConfigCodeEnum;
import com.yiren.backstage.config.enums.UnitNameEnum;
import com.yiren.backstage.currency.constant.SignalGConstant;
import com.yiren.backstage.currency.entity.SiteEntity;
import com.yiren.backstage.db.dao.bean.SynExamBean;
import com.yiren.backstage.db.dao.controller.UserDbController;
import com.yiren.dbaa.R;
import com.yiren.dbaa.currency.model.CheckBoxCommonModel;
import com.yiren.dbaa.currency.model.EdittextCommonModel;
import com.yiren.dbaa.currency.fragment.LazyLoadFragment;
import com.yiren.dbaa.module.project_edit.view.adapter.SelectParamAdapter;
import com.yiren.dbaa.util.DensityUtil;
import com.yiren.dbaa.view.toast.MessageBox;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @author lwb
 * @date : 2022/11/4 16:15
 * @description: 加减档
 */
public class JjdFragment extends LazyLoadFragment {

    @BindView(R.id.et_start_voice)
    EditText etStartVoice;
    @BindView(R.id.et_end_voice)
    EditText etEndVoice;
    @BindView(R.id.et_one_order)
    EditText etOneOrder;
    @BindView(R.id.et_two_order)
    EditText etTwoOrder;
    @BindView(R.id.et_three_order)
    EditText etThreeOrder;
    @BindView(R.id.et_four_order)
    EditText etFourOrder;
    @BindView(R.id.et_five_order)
    EditText etFiveOrder;
    @BindView(R.id.et_plus_gear_voice)
    EditText etPlusGearVoice;
    @BindView(R.id.et_sub_gear_voice)
    EditText etSubGearVoice;
    @BindView(R.id.et_play_space_time)
    EditText etPlaySpaceTime;
    @BindView(R.id.et_gear_tips_voice)
    EditText etGearTipsVoice;
    @BindView(R.id.cb_loose_finish)
    CheckBox cbLooseFinish;
    @BindView(R.id.cb_error_agree)
    CheckBox cbErrorAgree;
    @BindView(R.id.et_error_time)
    EditText etErrorTime;
    @BindView(R.id.et_single_complete)
    EditText etSingleComplete;
    @BindView(R.id.tv_single_unit)
    TextView tvSingleUnit;
    @BindView(R.id.et_gear_complete)
    EditText etGearComplete;
    @BindView(R.id.tv_gear_unit)
    TextView tvGearUnit;

    private UnitNameEnum singleUnit;
    private UnitNameEnum totalUnit;
    private List<String> selectList;
    private String selectString;

    private SiteEntity site;//考场信息
    public Map<String, Object> tempMap;//修改的保存参数map
    private boolean isPartner;
    private SynExamBean synExamBean;
    private Gson gs = new Gson();

    private List<EdittextCommonModel> edittextCommonModels;
    private List<CheckBoxCommonModel> checkBoxCommonModels;

    @Override
    protected int setContentView() {
        return R.layout.fragment_jjd;
    }

    @Override
    protected void init() {
        initData();
        setData();
        setEditText();
        setCheckBox();
    }

    private void initData() {
        site = (SiteEntity) getArguments().getSerializable("site");
        tempMap = new HashMap<>();
        isPartner = LoadConfigApi.loadUserParamConfig(getActivity()).isPartner();
        synExamBean = gs.fromJson(isPartner ? site.getPartneModifyVal() : site.getCoachModifyVal(), new TypeToken<SynExamBean>() {
        }.getType());
        if (null == synExamBean) synExamBean = new SynExamBean();
        selectList = new ArrayList<String>();
    }

    private void setData() {
        singleUnit = UnitNameEnum.valueOf((String) SignalGConstant.examConfigMap.get(SiteConfigCodeEnum.J14.toString()));
        tvSingleUnit.setText(singleUnit.getDescription());
        totalUnit = UnitNameEnum.valueOf((String) SignalGConstant.examConfigMap.get(SiteConfigCodeEnum.J16.toString()));
        tvGearUnit.setText(totalUnit.getDescription());
    }

    private void setEditText() {
        edittextCommonModels = new ArrayList<>();
        edittextCommonModels.add(new EdittextCommonModel(etStartVoice, SiteConfigCodeEnum.J17.toString()));
        edittextCommonModels.add(new EdittextCommonModel(etEndVoice, SiteConfigCodeEnum.J18.toString()));
        edittextCommonModels.add(new EdittextCommonModel(etOneOrder, SiteConfigCodeEnum.J1.toString()));
        edittextCommonModels.add(new EdittextCommonModel(etTwoOrder, SiteConfigCodeEnum.J2.toString()));
        edittextCommonModels.add(new EdittextCommonModel(etThreeOrder, SiteConfigCodeEnum.J3.toString()));
        edittextCommonModels.add(new EdittextCommonModel(etFourOrder, SiteConfigCodeEnum.J4.toString()));
        edittextCommonModels.add(new EdittextCommonModel(etFiveOrder, SiteConfigCodeEnum.J5.toString()));
        edittextCommonModels.add(new EdittextCommonModel(etPlusGearVoice, SiteConfigCodeEnum.J6.toString()));
        edittextCommonModels.add(new EdittextCommonModel(etSubGearVoice, SiteConfigCodeEnum.J7.toString()));
        edittextCommonModels.add(new EdittextCommonModel(etPlaySpaceTime, SiteConfigCodeEnum.J8.toString()));
        edittextCommonModels.add(new EdittextCommonModel(etGearTipsVoice, SiteConfigCodeEnum.J9.toString()));
        edittextCommonModels.add(new EdittextCommonModel(etErrorTime, SiteConfigCodeEnum.J12.toString()));
        edittextCommonModels.add(new EdittextCommonModel(etSingleComplete, SiteConfigCodeEnum.J13.toString()));
        edittextCommonModels.add(new EdittextCommonModel(etGearComplete, SiteConfigCodeEnum.J15.toString()));
        for (EdittextCommonModel model : edittextCommonModels) {
            model.getEt().setText(model.getInitValue());
            model.getEt().addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                }

                @Override
                public void afterTextChanged(Editable s) {
                    SignalGConstant.examConfigMap.put(model.getKey(), s.toString());
                    if (!s.toString().equals(model.getInitValue())) {
                        tempMap.put(model.getKey(), s.toString());
                    } else {
                        tempMap.remove(model.getKey());
                    }
                }
            });
        }
    }

    private void setCheckBox() {
        checkBoxCommonModels = new ArrayList<>();
        checkBoxCommonModels.add(new CheckBoxCommonModel(cbLooseFinish, SiteConfigCodeEnum.J10.toString()));
        checkBoxCommonModels.add(new CheckBoxCommonModel(cbErrorAgree, SiteConfigCodeEnum.J11.toString()));
        for (CheckBoxCommonModel model : checkBoxCommonModels) {
            model.getCb().setChecked(model.isInitValue());
            model.getCb().setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    SignalGConstant.examConfigMap.put(model.getKey(), isChecked);
                    if (isChecked != model.isInitValue()) {
                        tempMap.put(model.getKey(), isChecked);
                    } else {
                        tempMap.remove(model.getKey());
                    }
                }
            });
        }
    }

    @OnClick({R.id.tv_single_unit, R.id.tv_gear_unit, R.id.tv_save_param})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_single_unit:
                setDialogValues(1, tvSingleUnit);
                break;
            case R.id.tv_gear_unit:
                setDialogValues(2, tvGearUnit);
                break;
            case R.id.tv_save_param:
                if (tempMap.size() == 0) return;
                for (String key : tempMap.keySet()) {
                    synExamBean.getExamConfigMap().put(key, tempMap.get(key));
                }
                if (isPartner) {
                    site.setPartneModifyVal(gs.toJson(synExamBean));
                } else {
                    site.setCoachModifyVal(gs.toJson(synExamBean));
                }
                UserDbController.getInstance(false).update(site);
                MessageBox.show(getActivity(), "保存成功!");
                break;
        }
    }

    private void setDialogValues(int type, TextView tv) {
        selectList.clear();
        selectString = tv.getText().toString();
        UnitNameEnum[] unitNames = UnitNameEnum.values();
        for (int i = 0; i < unitNames.length; i++) {
            selectList.add(unitNames[i].getDescription());
        }
        showSelectDialog(type, tv);
    }

    /**
     * 弹出框选择（type 1:单个加减档  2：加减档项目 ）
     */
    public void showSelectDialog(int type, TextView tv) {
        Dialog dialog = new AlertDialog.Builder(getActivity()).create();
        dialog.show();
        WindowManager.LayoutParams params = dialog.getWindow().getAttributes();
        params.width = (DensityUtil.getScreenWidth(getActivity()) * 7) / 10;
        params.height = (DensityUtil.getScreenHeight(getActivity()) * 6) / 10;
        dialog.getWindow().setAttributes(params);
        Window window = dialog.getWindow();
        window.setContentView(R.layout.dialog_select_box);
        TextView tvTitle = (TextView) window.findViewById(R.id.tv_title);
        ListView lvList = (ListView) window.findViewById(R.id.lv_dialog_list);
        lvList.setDivider(null);// 去除listview的下划线
        tvTitle.setText(getResources().getString(R.string.select_unit_type));
        SelectParamAdapter adapter = new SelectParamAdapter(getActivity(), selectList, selectString);
        lvList.setAdapter(adapter);
        lvList.setOnItemClickListener((parent, view, position, id) -> {
            tv.setText(selectList.get(position));
            UnitNameEnum[] unitNames = UnitNameEnum.values();
            switch (type) {
                case 1:  //单个档位
                    if (!singleUnit.equals(unitNames[position])) {
                        SignalGConstant.examConfigMap.put(SiteConfigCodeEnum.J14.toString(), unitNames[position].toString());
                        tempMap.put(SiteConfigCodeEnum.J14.toString(), unitNames[position].toString());
                    } else {
                        tempMap.remove(SiteConfigCodeEnum.J14.toString());
                    }
                    break;
                case 2:  //加减档项目
                    if (!totalUnit.equals(unitNames[position])) {
                        SignalGConstant.examConfigMap.put(SiteConfigCodeEnum.J16.toString(), unitNames[position].toString());
                        tempMap.put(SiteConfigCodeEnum.J16.toString(), unitNames[position].toString());
                    } else {
                        tempMap.remove(SiteConfigCodeEnum.J16.toString());
                    }
                    break;
            }
            dialog.dismiss();
        });
    }

}